package com.topfinance.xml;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import com.topfinance.util.IBPSMsgFactory;

public class MsgHandlerFactory {

	/**
	 * 
	 * @param webFlow
	 * @return
	 */
	public static String doGenOutFlowMsg(String msgId, Map dataMap) {
		String rtnStr = "";
		try {
			Class bizClazz = MsgTypeFactory.getInstance().getBizLogicClassByMsgId(msgId);
			IMsgHandler msgHandler = (IMsgHandler) (bizClazz.newInstance());
			rtnStr = String.valueOf(msgHandler.doOutFlowMsg(dataMap));
		} catch (Exception e) {
			e.printStackTrace();
			// log.error("Generating xml file failed.",e);
		}
		return rtnStr;
	}

	public static void doInFlowMsg(String head, String xmlDataStr) {
		JAXBElement<Object> webFlowElement = null;
		try {
			String packageName = MsgTypeFactory.getInstance().getPackageByXML(xmlDataStr);

			JAXBContext jaxbContext = JAXBContext.newInstance(packageName);
			Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
			webFlowElement = (JAXBElement<Object>) unMarshaller
					.unmarshal(new StreamSource(new StringReader(xmlDataStr)));
			Class bizClazz = MsgTypeFactory.getInstance().getBizLogicClassByPackageName(packageName);
			IMsgHandler msg001Handler = (IMsgHandler) (bizClazz.newInstance());
			msg001Handler.doInFlowMsg(head, webFlowElement.getValue());
		} catch (Exception e) {
			e.printStackTrace();
			// log.error("Parsing xml to Object failed.",e);
		}
	} 

	public static void main(String[] args) {
		try {
//			FileInputStream fis = new FileInputStream(
//					"E:\\DevSpace\\ECADOS\\ecdsRepo\\ecadosEJB\\ecdsMsg\\ecds.001.001.01.xml");
//			byte[] bb = new byte[fis.available()];
//			fis.read(bb);
//			byte[] head = new byte[200];
//			
//			System.arraycopy(bb, 0, head, 0, 200);
//			String msg = new String(bb, 200, bb.length - 200);
//			doInFlowMsg(new String(head), msg);
//			Map map031 = new  HashMap();
//			map031.put("Accptnc", "Accptnc");
			
			String msg = IBPSMsgFactory.compose101Message();
			Hashtable hash = IBPSMsgFactory.fetchMessage(msg);	
			Map map = IBPSMsgFactory.convertMsgByTag(hash);
			String msgXml = doGenOutFlowMsg("ibps.101.001.01", map);
			System.out.println("[Msg101]" + "\n" + msgXml);

			// System.out.println(aDocument.getCommercialDraftRegisterRequest().getAccptr().getAcct().getAcctSvcr());
			// System.out.println("from aDocument:" +
			// Jaxb2Util.buildXml(aDocument));
			// File file = new File("d:\\123.xml");
			// Jaxb2Util.buildXml(aDocument,file);
		} catch (Exception ioe) {
			ioe.printStackTrace();
		}
	}
}
